<template>
  <div class="p-4">
    <div class="detailBox">
      <div class="detailhead">
        <div class="returnPreviousPage" @click="returnPreviousPage">
          <RollbackOutlined style="margin-right: 8px;" /> 返回
        </div>
        <div class="title">
          <div v-show="!edit" class="text">{{ data?.projectName }}</div>
          <a-input v-show="edit" class="inp" v-model:value="formState.projectName" />
        </div>
        <div class="butBox" @click="redact" v-show="!edit">
          <EditOutlined class="icon" />
          <div class="text">编辑</div>
        </div>
        <div class="saveBox" v-show="edit">
          <a-button class="cancel" @click="cancel">取消</a-button>
          <a-button class="saveBut" @click="saveProject">保存项目</a-button>
        </div>
      </div>
      <div class="informBox">
        <div class="titleBox">
          <Image :preview="false" class="icon" :src="projectManage2_icon"></Image>
          <div class="text">基本信息</div>
        </div>
        <div class="box">
          <a-descriptions :column="2"
            :labelStyle="{ backgroundColor: '#F3FBFF', color: '#4392C6', border: '1px solid #CAEAFA', width: '167px', }"
            :contentStyle="{ border: '1px solid #CAEAFA', width: '622px' }" bordered>
            <a-descriptions-item label="系统编号">
              <!-- <div v-show="edit"><a-input style="width: 100%;" /></div> -->
              <!-- <div v-show="!edit"></div> -->
              {{ data?.projectNo }}
            </a-descriptions-item>
            <a-descriptions-item label="客户名称">
              <div v-show="edit"><a-input style="width: 100%;" v-model:value="formState.customerName" /></div>
              <div v-show="!edit">{{ data?.customerName }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="创建人">
              <div class="creator">
                <UserOutlined class="icon" /> {{ data?.createBy }}
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="所在地区">
              <div v-show="edit" style="width: 100%;">
                <JAreaLinkage v-model:value="location2" :showArea="false" @stateVal="stateVal"></JAreaLinkage>
              </div>
              <div v-show="!edit">{{ data?.location }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="项目地址">
              <div v-show="edit">
                <div class="mapLocalBox">
                  <div class="inpBox" @click="dsMap(true)">
                    <a-input v-model:value="form.address" ref="inputRef"></a-input>
                  </div>
                  <div v-show="displayMap" class="MapBox" @click="() => { inputRef.value.focus(); }">
                    <div class="mapSelectBox">
                      <a-select style="width: 100%;" v-model:value="keywords" show-search
                        :default-active-first-option="false" :show-arrow="false" :filter-option="false"
                        :not-found-content="null" @search="remoteMethod" @change="">
                        <template #suffixIcon>
                          <SearchOutlined />
                        </template>

                        <a-select-option v-for="item in options" @click="currentSelect(item)" :value="item.id">{{
                          item.name }}</a-select-option>
                      </a-select>
                    </div>
                    <div id="container"></div>
                    <div class="Mapbut">
                      <a-button type="primary" @click="dsMap(false)">确定</a-button>
                    </div>
                  </div>
                </div>
              </div>
              <div v-show="!edit">{{ form.address }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="项目负责人">
              <div v-show="edit">
                <a-select v-model:value="formState.adminList" style="width: 100%;"
                  :field-names="{ label: 'realname', value: 'id', options: 'options' }" mode="multiple" :options="user"
                  @change="adminChange" placeholder="请选择"></a-select>
              </div>
              <div v-show="!edit" style="display: flex;flex-wrap: wrap;align-items: center;">
                <div class="creator" style="margin-right: 12px;" v-for="item in memberQuery(data?.adminList)">
                  <UserOutlined class="icon" /> {{ item }}
                </div>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="项目成员">
              <div v-show="edit">
                <a-select v-model:value="formState.memberList"
                  :field-names="{ label: 'realname', value: 'id', options: 'options' }" @deselect="deselect"
                  mode="multiple" :options="user" style="width: 100%;" placeholder="请选择"></a-select>
              </div>
              <div v-show="!edit" style="display: flex;flex-wrap: wrap;align-items: center;">
                <div class="creator" style="margin-right: 12px;" v-for="item in memberQuery(data?.memberList)">
                  <UserOutlined class="icon" /> {{ item }}
                </div>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="项目状态">
              <div v-show="edit">
                <a-select style="width: 100%;" v-model:value="formState.state" :options="projectState"
                  placeholder="请选择"></a-select>
              </div>
              <div v-show="!edit">
                <div :class="'stateBox' + data?.state">
                  {{ ['进行中', '暂存', '已完结'][data?.state] }}
                </div>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="项目周期">
              <div v-show="edit">
                <a-range-picker format="YYYY/MM/DD" @change="projectTimeChange" v-model:value="projectTime" />
              </div>
              <div v-show="!edit">{{ data?.startDate + '~' + data?.endDate }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="项目预算">
              <div v-show="edit">
                <a-select v-model:value="formState.budget" :options="budgetOptins" style="width: 100%;"
                  placeholder="请选择"></a-select>
              </div>
              <div v-show="!edit">{{ ['10万元以下', '10-50万元', '50-100万元', '100-500万元', '500-1000万元',
                '1000万元以上'][data?.budget] }}
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="titleBox">
          <Image :preview="false" class="icon" :src="projectManage1_icon"></Image>
          <div class="text">附加信息</div>
        </div>
        <div class="box">
          <a-descriptions :column="1"
            :labelStyle="{ backgroundColor: '#F3FBFF', color: '#4392C6', border: '1px solid #CAEAFA', width: '167px' }"
            :contentStyle="{ border: '1px solid #CAEAFA' }" bordered>
            <a-descriptions-item label="项目需求">
              <div v-show="edit"><a-textarea :rows="4" v-model:value="formState.demandContent" show-count
                  :maxlength="300" /></div>
              <div v-show="!edit">{{ data?.demandContent }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="其他信息">
              <div v-show="edit"><a-textarea v-model:value="formState.otherInfo" :rows="4" show-count :maxlength="300" />
              </div>
              <div v-show="!edit">{{ data?.otherInfo }}</div>
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="titleBox">
          <Image :preview="false" class="icon" :src="projectManage1_icon"></Image>
          <div class="text">相关数据</div>
        </div>
        <div class="relayDataBox">
          <div class="relayData">
            <div class="left">
              <div class="img">

                <Image :preview="false" :src="img2_icon"></Image>
              </div>
              <div class="info">
                <div class="title">图片</div>
                <div class="number">{{ data?.imgNum }} 条</div>
              </div>
            </div>
            <div class="right">
              <div class="title">今日 +{{ data?.imgTodayNum }}</div>
              <Image :preview="false" class="icon" :src="projectManage3_icon"></Image>
            </div>
          </div>

          <div class="relayData">
            <div class="left">
              <div class="img">
                <Image :preview="false" :src="video_icon"></Image>
              </div>
              <div class="info">
                <div class="title">视频</div>
                <div class="number">{{ data?.videoNum }} 条</div>
              </div>
            </div>
            <div class="right">
              <div class="title">今日 +{{ data?.videoTodayNum }}</div>
              <Image :preview="false" class="icon" :src="projectManage3_icon"></Image>
            </div>
          </div>

          <div class="relayData">
            <div class="left">
              <div class="img">
                <Image :preview="false" :src="panoramaPicture_icon"></Image>
              </div>
              <div class="info">
                <div class="title">全景图</div>
                <div class="number">{{ data?.panoramaNum }} 条</div>
              </div>
            </div>
            <div class="right">
              <div class="title">今日 +{{ data?.panoramaTodayNum }}</div>
              <Image :preview="false" class="icon" :src="projectManage3_icon"></Image>
            </div>
          </div>

          <div class="relayData">
            <div class="left">
              <div class="img">
                <Image :preview="false" :src="image_icon"></Image>
              </div>
              <div class="info">
                <div class="title">正射影像</div>
                <div class="number">{{ data?.positiveProjectiveImageNum }} 条</div>
              </div>
            </div>
            <div class="right">
              <div class="title">今日 +{{ data?.positiveProjectiveImageTodayNum }}</div>
              <Image :preview="false" class="icon" :src="projectManage3_icon"></Image>
            </div>
          </div>

          <div class="relayData">
            <div class="left">
              <div class="img">
                <Image :preview="false" :src="photography_icon"></Image>
              </div>
              <div class="info">
                <div class="title">倾斜摄影</div>
                <div class="number">{{ data?.obliquePhotographNum }} 条</div>
              </div>
            </div>
            <div class="right">
              <div class="title">今日 +{{ data?.obliquePhotographTodayNum }}</div>
              <Image :preview="false" class="icon" :src="projectManage3_icon"></Image>
            </div>
          </div>

        </div>
      </div>
      <div class="saveBox" v-show="edit">

      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { EditOutlined, TagOutlined, UserOutlined, RollbackOutlined } from '@ant-design/icons-vue';
import { useRouter, useRoute } from "vue-router";
import { queryById, UserList, editAPi } from './data.api'
import { JAreaLinkage } from '/@/components/Form';
import dayjs, { Dayjs } from 'dayjs';
import { Image } from 'ant-design-vue';
import image_icon from '@/assets/icons/projectManage/image-icon.svg';
import img2_icon from '@/assets/icons/projectManage/img2-icon.svg';
import video_icon from '@/assets/icons/projectManage/video-icon.svg';
import panoramaPicture_icon from '@/assets/icons/projectManage/panoramaPicture-icon.svg';
import photography_icon from '@/assets/icons/projectManage/photography-icon.svg';
import projectManage1_icon from '@/assets/icons/projectManage/projectManage1-icon.svg';
import projectManage2_icon from '@/assets/icons/projectManage/projectManage2-icon.svg';
import projectManage3_icon from '@/assets/icons/projectManage/projectManage3-icon.svg';
import AMapLoader from "@amap/amap-jsapi-loader";
const router = useRoute()
const routerR = useRouter();
let data = ref();
let user = ref();
let location2 = ref()
let projectTime = ref()
let edit = ref<Boolean>(false)
let formState = reactive({
  customerName: '',
  projectName: '',
  location: '',
  adminList: [],
  memberList: [],
  state: '',
  budget: '',
  demandContent: '',
  otherInfo: '',

  startDate: '',
  endDate: '',
  provinceCode: '',
  cityCode: ''
})


let displayMap = ref<boolean>(false) // 是否显示地图
let map = null;  // 地图实例
let marker = null; // 标记点
let geoCoder = ref()// 地址逆解析
let AutoComplete = ref()  // 搜索提示
let keywords = ref()  // 搜索关键字
let inputRef = ref()
// 搜索节流阀
let loading = ref(false)
// 搜索提示信息
let options = ref([])

let form = reactive({
  lng: '',
  lat: '',
  address: '',
  adcode: '',
})

window._AMapSecurityConfig = {
  securityJsCode: 'f151338307a532a145225cbd9c1c714b',
}

AMapLoader.load({
  key: "59c61f064c552f2ace25ff0c1d6465a7",
  version: "2.0",
  plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
}).then((AMap) => {
  map = new AMap.Map("container", {
    // 设置地图容器id
    // viewMode: "3D", // 是否为3D地图模式
    zoom: 11, // 初始化地图级别
    // center: [116.397428, 39.90923], // 初始化地图中心点位置
  });


  geoCoder.value = new AMap.Geocoder({
    city: "010", //城市设为北京，默认：“全国”
    radius: 1000, //范围，默认：500
  });

  AutoComplete = new AMap.AutoComplete({ city: "全国" });

  map.on('click', (e) => {
    form.lng = e.lnglat.getLng();
    form.lat = e.lnglat.getLat();
    // console.log(e.lnglat.getLng(), e.lnglat.getLat())
    console.log(e)
    removeMarker()
    setMapMarker()
  })

}).catch((e) => {
  console.log(e);
});

function dsMap(type: boolean) {
  displayMap.value = type
}

//返回上一页
function returnPreviousPage() {
  routerR.go(-1)
}

function setMapMarker() {
  // 自动适应显示想显示的范围区域
  map.setFitView();
  marker = new AMap.Marker({
    map: map,
    position: [form.lng, form.lat],
  });
  toGeoCoder()
  map.setFitView();
  map.add(marker);
}

function removeMarker() {
  if (marker) {
    map.remove(marker);
  }
}

// 逆解析地址
function toGeoCoder() {
  let lnglat = [form.lng, form.lat];
  // let lnglat = [114.086838, 22.537209];
  console.log(lnglat, 'lnglat')
  geoCoder.value.getAddress(lnglat, (status, result) => {
    console.log(status, result, 'result')
    if (status === "complete" && result.regeocode) {
      form.address = result.regeocode.formattedAddress;
    }
  });
  console.log(form, 'form')
}
let timer = null;
// 搜索
function remoteMethod(query) {
  console.log(query);
  if (query !== "") {
    if (timer) {
      clearTimeout(timer); // 清除之前的定时器
    }
    loading.value = true;
    timer = setTimeout(() => {
      loading.value = false;
      console.log('定时器触发')
      AutoComplete.search(query, (status, result) => {
        options.value = result.tips;
        console.log(options.value, 'options.value')
      });
    }, 1000);
  } else {
    console.log('清空了opt');
    options.value = [];
  }
}

// 选中提示
function currentSelect(val) {
  console.log(val, 'currentSelect');
  // 清空时不执行后面代码
  if (!val) {
    return;
  }

  form.lng = val.location.lng
  form.lat = val.location.lat
  form.address = val.district + val.address + val.name
  form.adcode = val.adcode

  // 清除点
  removeMarker();
  // 标记点
  setMapMarker();
}


function redact() {
  edit.value = true;
  console.log(edit.value, '编辑按钮', router.query.id);
}
function cancel() {
  edit.value = false;
}

function projectTimeChange(e) {
  console.log(e, projectTime, 'e')
  const data1 = new Date(e[0].$d)
  const data2 = new Date(e[1].$d)
  formState.startDate = formatDate(data1);
  formState.endDate = formatDate(data2);
  console.log(formState.startDate, formState.endDate)
  const tiem = new Date(e[0])
  console.log(tiem, 'tiem')
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  // const hours = date.getHours().toString().padStart(2, '0');
  // const minutes = date.getMinutes().toString().padStart(2, '0');
  // const seconds = date.getSeconds().toString().padStart(2, '0');
  // ${hours}:${minutes}:${seconds}
  return `${year}-${month}-${day} `;
}

function stateVal(e) {
  const arr = e[0].map(item => item.label).join('/')
  formState.location = arr
  console.log(arr, 'e')
}

function adminChange() {
  const array = [...formState.adminList, ...formState.memberList]
  formState.memberList = [...new Set(array)]
}

function deselect(e) {
  if (formState.adminList.includes(e)) {
    formState.memberList.push(e)
  }
}

function memberQuery(val) {
  if (typeof val !== 'string') {
    // 如果 val 不是一个字符串，你可以采取适当的处理方式，如返回一个错误或空数组
    return [];
  }
  const arr = val.split(',');
  const matchingItems = [];
  if (user.value && Array.isArray(user.value)) {
    for (let i = 0; i < arr.length; i++) {
      user.value.forEach(item => {
        if (item.id == arr[i]) {

          matchingItems.push(item.realname)
        }
      })
    }
  }

  console.log(matchingItems, 'matchingItems');
  // if (matchingItems.length == 1) {
  //   return matchingItems.join(',')
  // } else {
  return matchingItems;
  // }

}

const projectState = ref([
  {
    label: '进行中',
    value: '0',
  },
  {
    label: '暂存',
    value: '1',
  },
  {
    label: '已完结',
    value: '2',
  },
])

const budgetOptins = ref([
  {
    label: '10万元以下',
    value: '0',
  },
  {
    label: '10-15万元',
    value: '1',
  },
  {
    label: '50-100万元',
    value: '2',
  },
  {
    label: '100-500万元',
    value: '3',
  },
  {
    label: '500-1000万元',
    value: '4',
  },
  {
    label: '1000万元以上',
    value: '5',
  },
])

async function saveProject() {
  formState.provinceCode = location2.value[0]
  formState.cityCode = location2.value[1]
  let { adminList, provinceCode, cityCode, customerName, memberList, startDate, endDate, state, budget, demandContent, otherInfo, projectName, location, customerType } = formState
  const res = await editAPi({
    id: router.query.id,
    adminList: adminList.join(','),
    memberList: memberList.join(','),
    provinceCode,
    cityCode,
    customerName,
    budget,
    demandContent,
    otherInfo,
    projectName,
    startDate,
    endDate,
    state,
    location,
    customerType,
    longitude: form.lng,
    latitude: form.lat
  });

  getDate()
  cancel()
}
const dateFormat = 'YYYY/MM/DD';
async function getDate() {
  const res = await queryById({ id: router.query.id });
  data.value = res;
  const res2 = await UserList()
  user.value = res2.records;
  console.log(user.value, 'res2');
  formState.customerName = res.customerName;
  formState.projectName = res.projectName;
  location2.value = [res.provinceCode, res.cityCode]
  formState.adminList = res.adminList.split(',')
  formState.memberList = res.memberList.split(',')
  formState.state = res.state
  formState.budget = res.budget
  formState.demandContent = res.demandContent
  formState.otherInfo = res.otherInfo
  formState.location = res.location

  formState.startDate = res.startDate
  formState.endDate = res.endDate

  projectTime.value = [
    dayjs(res.startDate, dateFormat),
    dayjs(res.endDate, dateFormat),
  ]

  form.lng = res.longitude
  form.lat = res.latitude

  let lnglat = [res.longitude, res.latitude];
  geoCoder.value.getAddress(lnglat, (status, result) => {
    console.log(status, result, 'result')
    if (status === "complete" && result.regeocode) {
      form.address = result.regeocode.formattedAddress;
    }
  });
}

onMounted(async () => {
  getDate()
  // projectTime.value = dayjs(res.createTime, 'YYYY-MM-DD HH:mm:ss').format
})
</script>
<style lang="less" scoped>
/deep/ .ant-select-show-arrow {
  width: 100%;
}

#container {
  width: 447px;
  height: 229px
}

.Mapbut {
  position: absolute;
  right: 7px;
  bottom: 7px;
}


.mapLocalBox {
  position: relative;

  .inpBox {
    // width: 253px;
    // height: 32px;
    // border: 1px solid #d9d9d9;
    // border-radius: 2px;
  }

  .MapBox {
    position: absolute;
    padding: 7px;
    z-index: 100;
    background-color: #FFFFFF;
    box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.09);
    border-radius: 4px;

    .mapSelectBox {
      width: 246px;
      position: absolute;
      top: 11px;
      left: 13px;
      z-index: 1;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.09);
    }
  }
}

.p-4 {
  .detailBox {
    .detailhead {
      display: flex;
      background: linear-gradient(301deg, rgba(82, 157, 204, 0.92) 0%, #4090C6 100%);
      border: 1px solid rgba(50, 163, 235, 0.23);
      padding: 13px 21px;
      position: relative;
      justify-content: flex-end;
      height: 50px;

      .returnPreviousPage {
        font-size: 14px;
        font-weight: 400;
        color: #FFFFFF;
        left: 26px;
        position: absolute;
        cursor: pointer;
        display: flex;
        align-items: center;
      }

      .title {
        width: 405px;
        height: 40px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        color: #FFFFFF;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        align-items: center;
        justify-content: center;

        .text {}

        .inp {
          background: linear-gradient(360deg, rgba(214, 241, 255, 0.25) 0%, rgba(194, 234, 255, 0.27) 100%);
          border-radius: 20px;
          border: 2px solid rgba(255, 255, 255, 0.5);
          backdrop-filter: blur(2px);
          color: #FFFFFF;
          font-size: 16px;
          text-align: center;
        }
      }

      .butBox {
        display: flex;
        align-items: center;
        cursor: pointer;

        .icon {
          color: #FFFFFF;
          margin-right: 11px;
        }

        .text {
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #FFFFFF;
        }
      }
    }

    .informBox {
      padding: 24px 24px;
      background-color: #FFFFFF;

      .titleBox {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        .icon {
          font-size: 15px;
          color: #4090C6;
          margin-right: 11px;
        }

        .text {
          font-size: 16px;
          font-weight: 700;
          color: #333333;
        }
      }

      .box {
        margin-bottom: 20px;

        div {}

        .creator {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #333333;

          .icon {
            margin-right: 9px;
          }
        }

        .stateBox0 {
          width: 46px;
          height: 19px;
          background-color: #E4F4FC;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #17ABD1;
          text-align: center;
        }

        .stateBox1 {
          width: 46px;
          height: 19px;
          background-color: #FCF7E4;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ED8B2B;
          text-align: center;
        }

        .stateBox1 {
          width: 46px;
          height: 19px;
          background-color: #FCF7E4;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ED8B2B;
          text-align: center;
        }

        .stateBox2 {
          width: 46px;
          height: 19px;
          background-color: #E7F7F1;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #15B37A;
          text-align: center;
        }
      }

      .relayDataBox {
        display: flex;

        .relayData {
          height: 101px;
          display: flex;
          align-items: center;
          padding: 25px 23px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-right: 15px;
          flex: 25%;
          border-radius: 4px;

          .left {
            display: flex;
            align-items: center;

            .img {
              width: 50px;
              height: 50px;
              border-radius: 50%;
              // background-color: #10bedd;
              margin-right: 12px;
            }

            .info {

              // text-align: center;
              .title {}

              .number {}
            }


          }

          .right {
            display: flex;
            align-items: center;

            .title {
              margin-right: 5px;
            }

            .icon {}
          }
        }

        .relayData:nth-child(odd) {
          background: linear-gradient(360deg, #FFFFFF 0%, rgba(236, 252, 255, 0.9) 100%);
        }

        .relayData:nth-child(even) {
          background: linear-gradient(360deg, #FFFFFF 0%, rgba(231, 246, 255, 0.9) 100%, rgba(231, 246, 255, 0.9) 100%);
        }
      }

    }

    .saveBox {
      // background-color: #FFFFFF;
      // border-top: 1px solid rgba(204, 204, 204, 0.5);
      // padding: 20px 25px;
      // text-align: end;
      position: absolute;
      right: 24px;
      top: 8px;

      .cancel {
        width: 88px;
        height: 32px;
        border-radius: 2px;
        border: 1px solid #CCCCCC;
        font-weight: 400;
        color: #666666;
        margin-right: 20px;
      }

      .saveBut {
        width: 88px;
        height: 32px;
        background: linear-gradient(315deg, #2C9AD6 0%, #167DB5 100%);
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.16);
        border-radius: 2px;
        font-weight: 400;
        font-size: 14px;
        color: #FFFFFF;
      }
    }
  }
}
</style>
